package com.hhf.springboot.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hhf.springboot.annotation.AuthCheck;
import com.hhf.springboot.common.*;
import com.hhf.springboot.constant.ProjectStatusConstant;
import com.hhf.springboot.constant.UserConstant;
import com.hhf.springboot.exception.BusinessException;
import com.hhf.springboot.exception.ThrowUtils;
import com.hhf.springboot.model.dto.serviceProject.ServiceProjectAddRequest;
import com.hhf.springboot.model.dto.serviceProject.ServiceProjectEditRequest;
import com.hhf.springboot.model.dto.serviceProject.ServiceProjectQueryRequest;
import com.hhf.springboot.model.dto.serviceProject.ServiceProjectUpdateRequest;
import com.hhf.springboot.model.entity.ServiceProject;
import com.hhf.springboot.model.entity.User;
import com.hhf.springboot.model.vo.ServiceProjectVO;
import com.hhf.springboot.service.ServiceProjectService;
import com.hhf.springboot.service.UserService;
import com.hhf.springboot.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 服务项目信息接口
 *
 * @author hhf
 * @from <a href="https://gitee.com/hanhuaifei/projects">我的gitee</a>
 * @Date 2024/9/26
 */
@RestController
@RequestMapping("/serviceProject")
@Slf4j
public class ServiceProjectController {

    @Resource
    private ServiceProjectService serviceProjectService;

    @Resource
    private UserService userService;


    /**
     * 浏览
     *
     * @param serviceProjectId
     */
    @GetMapping("/click")
    public BaseResponse<Long> doServiceProjectClick(Long serviceProjectId) {
        if (serviceProjectId == null || serviceProjectId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        return Result.success(serviceProjectService.doClick(serviceProjectId));
    }


    // region 增删改查

    /**
     * 创建服务项目信息
     *
     * @param serviceProjectAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addServiceProject(@RequestBody ServiceProjectAddRequest serviceProjectAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(serviceProjectAddRequest == null, ErrorCode.PARAMS_ERROR);
        // 在此处将实体类和 DTO 进行转换
        ServiceProject serviceProject = new ServiceProject();
        BeanUtils.copyProperties(serviceProjectAddRequest, serviceProject);
        // 数据校验
        serviceProjectService.validServiceProject(serviceProject, true);
        // 填充默认值
        User loginUser = userService.getLoginUser(request);
        serviceProject.setUserId(loginUser.getId());
        serviceProject.setStatus(ProjectStatusConstant.OPEN);
        serviceProject.setClickNum(0L);

        // 写入数据库
        boolean result = serviceProjectService.save(serviceProject);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newServiceProjectId = serviceProject.getId();
        return Result.success(newServiceProjectId);
    }

    /**
     * 删除服务项目信息
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteServiceProject(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        ServiceProject oldServiceProject = serviceProjectService.getById(id);
        ThrowUtils.throwIf(oldServiceProject == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldServiceProject.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = serviceProjectService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return Result.success(true);
    }

    /**
     * 更新服务项目信息（仅管理员可用）
     *
     * @param serviceProjectUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateServiceProject(@RequestBody ServiceProjectUpdateRequest serviceProjectUpdateRequest) {
        if (serviceProjectUpdateRequest == null || serviceProjectUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 在此处将实体类和 DTO 进行转换
        ServiceProject serviceProject = new ServiceProject();
        BeanUtils.copyProperties(serviceProjectUpdateRequest, serviceProject);
        // 数据校验
        serviceProjectService.validServiceProject(serviceProject, false);
        // 判断是否存在
        long id = serviceProjectUpdateRequest.getId();
        ServiceProject oldServiceProject = serviceProjectService.getById(id);
        ThrowUtils.throwIf(oldServiceProject == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = serviceProjectService.updateById(serviceProject);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return Result.success(true);
    }

    /**
     * 根据 id 获取服务项目信息（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<ServiceProjectVO> getServiceProjectVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        ServiceProject serviceProject = serviceProjectService.getById(id);
        ThrowUtils.throwIf(serviceProject == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return Result.success(serviceProjectService.getServiceProjectVO(serviceProject, request));
    }

    /**
     * 分页获取服务项目信息列表（仅管理员可用）
     *
     * @param serviceProjectQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<ServiceProject>> listServiceProjectByPage(@RequestBody ServiceProjectQueryRequest serviceProjectQueryRequest) {
        long current = serviceProjectQueryRequest.getCurrent();
        long size = serviceProjectQueryRequest.getPageSize();
        // 查询数据库
        Page<ServiceProject> serviceProjectPage = serviceProjectService.page(new Page<>(current, size),
                serviceProjectService.getQueryWrapper(serviceProjectQueryRequest));
        return Result.success(serviceProjectPage);
    }

    /**
     * 分页获取服务项目信息列表（封装类）
     *
     * @param serviceProjectQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<ServiceProjectVO>> listServiceProjectVOByPage(@RequestBody ServiceProjectQueryRequest serviceProjectQueryRequest,
                                                               HttpServletRequest request) {
        long current = serviceProjectQueryRequest.getCurrent();
        long size = serviceProjectQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<ServiceProject> serviceProjectPage = serviceProjectService.page(new Page<>(current, size),
                serviceProjectService.getQueryWrapper(serviceProjectQueryRequest));
        // 获取封装类
        return Result.success(serviceProjectService.getServiceProjectVOPage(serviceProjectPage, request));
    }

    /**
     * 分页获取当前登录用户创建的服务项目信息列表
     *
     * @param serviceProjectQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<ServiceProjectVO>> listMyServiceProjectVOByPage(@RequestBody ServiceProjectQueryRequest serviceProjectQueryRequest,
                                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(serviceProjectQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        serviceProjectQueryRequest.setUserId(loginUser.getId());
        long current = serviceProjectQueryRequest.getCurrent();
        long size = serviceProjectQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<ServiceProject> serviceProjectPage = serviceProjectService.page(new Page<>(current, size),
                serviceProjectService.getQueryWrapper(serviceProjectQueryRequest));
        // 获取封装类
        return Result.success(serviceProjectService.getServiceProjectVOPage(serviceProjectPage, request));
    }

    /**
     * 编辑服务项目信息（给用户使用）
     *
     * @param serviceProjectEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editServiceProject(@RequestBody ServiceProjectEditRequest serviceProjectEditRequest, HttpServletRequest request) {
        if (serviceProjectEditRequest == null || serviceProjectEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 在此处将实体类和 DTO 进行转换
        ServiceProject serviceProject = new ServiceProject();
        BeanUtils.copyProperties(serviceProjectEditRequest, serviceProject);
        // 数据校验
        serviceProjectService.validServiceProject(serviceProject, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = serviceProjectEditRequest.getId();
        ServiceProject oldServiceProject = serviceProjectService.getById(id);
        ThrowUtils.throwIf(oldServiceProject == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldServiceProject.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = serviceProjectService.updateById(serviceProject);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return Result.success(true);
    }

    /**
    * 日新增统计服务项目信息
    *
    * @return
    */
    @PostMapping("/day/newly/added")
    public BaseResponse<List<DataGroupByDateDTO>> dayNewlyAddedServiceProject() {
        // 今天
        Date endDate = DateUtils.getNow();
        // 30天以前
        Date beginDate = DateUtils.dayAfter(endDate, -30);
        // 查询
        List<DataGroupByDateDTO> serviceProjectDataList = serviceProjectService.countByDay(beginDate, endDate);
        //返回结果
        return Result.success(serviceProjectDataList);

    }

    // endregion
}
